package com.zhiyou100.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.zhiyou100.entity.ResponseJson;
import com.zhiyou100.entity.TabUser;
import com.zhiyou100.mapper.TabUserMapper;
import com.zhiyou100.service.ITabUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhiyou100.util.md5.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 杨磊
 * @since 2020-10-09
 */
@Service
public class TabUserServiceImpl extends ServiceImpl<TabUserMapper, TabUser> implements ITabUserService {

    @Autowired
    private TabUserMapper mapper;

    @Override
    public ResponseJson<Object> login(String name, String pwd, HttpServletRequest request) {
        if (Validator.isEmpty(name) || Validator.isEmpty(pwd)) {
            // 密码或者用户名 为空
            return new ResponseJson<>(500, "用户名或者密码为空", null);
        }
        // 根据用户名获取一个用户
        final TabUser userByUserName = mapper.selectByMap(
                Dict.create()
                        .set("uname", name))
                .get(0);
        if (Validator.isNull(userByUserName)) {
            // 用户名不存在
            return new ResponseJson<>(500, "用户名不存在", null);
        }
        if (Validator.isFalse(Md5Util.verify(pwd, null, userByUserName.getUpwd()))) {
            // 密码不一致
            return new ResponseJson<>(500, "密码错误", null);
        }
        // 更改状态
        userByUserName.setUstatus("1");
        // 更新
        mapper.updateById(userByUserName);
        // 放入 session 中
        request.getSession().setAttribute("user", userByUserName);
        // 响应


        String template = "登陆成功！，当前处理请求的服务器的地址 {}，Session 中的 user 信息 {} ";
        // 当前处理请求的服务器
        final String localAddr = request.getLocalAddr();
        //Session  中的 user 信息
        final Object user = request.getSession().getAttribute("user");
        // 格式化后的字符串
        final String format = StrUtil.format(template, localAddr, user);

        return new ResponseJson<>(200, format, userByUserName);
    }

    @Override
    public ResponseJson<Object> logout(Integer uid, HttpServletRequest request) {
        if (Validator.isNull(uid)) {
            // 为 null
            return new ResponseJson<>(500, "uid 为 null", null);
        }
        final TabUser tabUser = mapper.selectById(uid);
        if (Validator.isNull(tabUser)) {
            // 不存在该 uid
            return new ResponseJson<>(500, " 不存在该 uid", null);
        }
        tabUser.setUstatus("0");
        mapper.updateById(tabUser);
        request.getSession().invalidate();
        return new ResponseJson<>(200, tabUser.getUname() + " 登出成功！", tabUser);

    }
}
